package cn.datawin.cotask.client;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import cn.datawin.spider.httputil.HttpClientService;
import cn.datawin.spider.httputil.HttpClientService_2_1;
import cn.datawin.spider.httputil.HttpService;

public class ClientPool {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	public static Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(300).build();
	
	private static ClientPool pool = new ClientPool();
	
	private ClientPool(){};
	
	public static ClientPool getPool(){
		return pool;
	}
	
	public static HttpService newClient(String id){
		return pool.build(id);
	}
	
	public static HttpService get(String id){
		return pool.getCache(id);
	}
	
	public HttpService build(String id) {
		HttpService service = new HttpClientService_2_1(new ThreadSafeClientConnManager());
		cache.put(id, service);
		return service;
	}


	public void destory(String id) {
		cache.invalidate(id);
	}

	public HttpService getCache(final String id) {
		try {
			return (HttpService) cache.get(id, new Callable<Object>() {
				@Override
				public Object call() throws Exception {
					return new HttpClientService_2_1(new ThreadSafeClientConnManager());
				}
			});
		} catch (ExecutionException e) {
			log.error("getCache", e);
			return null;
		}
	}
}
